from flask import Flask, redirect,  url_for,send_file, request, render_template,send_from_directory,Response,make_response
from flask_cors import *
import hashlib
import base64
from packages.semail import SendCode
from packages.mysql import search
import os
import json
app = Flask(__name__)
aa=search()
zips = ['zip', 'rar']
images = ['jpg', 'png', 'gif', 'jpeg']
@app.route('/login',methods = ['GET', 'POST'])
@cross_origin(supports_credentials=True)
def login():
    json = request.json
    zhanghao=str(json['zh'])
    print(type(zhanghao))
    mima=json['mm']
    print(zhanghao)
    upassword=aa.password(zhanghao)
    if(upassword==mima):
        resp = make_response('success')
        resp.set_cookie('zhanghao', zhanghao,max_age=36000)
        resp.set_cookie('mima',mima,max_age=36000)
        return resp
    return '登录失败'

@app.route('/upload', methods = ['GET', 'POST'])
@cross_origin(supports_credentials=True)
def upload_file():
    if request.method == 'POST':
        road=request.headers.get('zichen')
        data = request.files
        print(type(data))
        file = data['file']
        # 文件写入磁盘
        file.save(f'{road}/'+file.filename)
        return 'file uploaded successfully'
@app.route('/sendmail', methods=['GET'])
@cross_origin(supports_credentials=True)
def sendcode():
    mail = SendCode()
    email=request.args.get('mail')
    code=mail.sedcode(email)
    hl = hashlib.md5()
    hl.update(str(code).encode(encoding='utf8'))
    md5 = hl.hexdigest()
    resp=make_response('success')
    resp.set_cookie('code', md5,max_age=360)
    return resp

@app.route('/datalist', methods=['GET', 'POST'])
@cross_origin(supports_credentials=True)
def getdata():
    zhanghao=request.cookies.get('zhanghao')
    data = []

    lists = os.listdir(f'{zhanghao}')
    for i in lists:
        zz = {}
        file = i.split('.')
        zz['name'] = i
        if (file[-1] in zips):
            zz['icon'] = 'box'
        else:
            zz['icon'] = 'Picture'
        data.append(zz)
    response=json.dumps(data)
    return response,200,{"Content-Type":"application/json"}
@app.route('/Download', methods=['GET','POST'])
@cross_origin(supports_credentials=True)
def Download():
    name = request.args.get('name')
    houzhui=name.split('.')
    print(name)
    zhanghao=request.cookies['zhanghao']
    img_path=f"{zhanghao}/{name}"
    if(houzhui[-1] in images):
        with open(img_path, 'rb') as img_f:
            img_stream = img_f.read()
            img_stream = base64.b64encode(img_stream).decode()
        return img_stream
    return send_from_directory(f"{zhanghao}", f"{name}", as_attachment=True)
@app.route('/register', methods=['GET','POST'])
@cross_origin(supports_credentials=True)
def register():
    data=request.get_json()
    print(data)
    hl = hashlib.md5()
    hl.update(data['code'].encode(encoding='utf8'))
    code = hl.hexdigest()
    if(code==data['md5']):
        aa.usercreate(data['username'],data['password'],data['mail'])
        os.mkdir(f"./{data['username']}")
        return '注册成功'
    return '验证码错误'
@app.route('/images', methods=['GET','POST'])
@cross_origin(supports_credentials=True)
def Images():
        return send_from_directory('1535497815/', '1.jpg')

if __name__ == '__main__':
    app = Flask(__name__)
